package com.eb.bi.common.util;

/*该类实现了对数据库连接和查询操作的封装，
 * 使用方法是直接调用该类的getInstance方法创建一个实例，
 * 调用该实例的相关方法即可
 * */
import java.sql.*;
public class DBConnection {
	/*
	 * // Oracle数据库连接URL private final static String db_url =
	 * "jdbc:oracle:thin:@10.1.70.35:1521:samplebi1";
	 * 
	 * // Oracle数据库连接驱动 private final static String db_driver =
	 * "oracle.jdbc.driver.OracleDriver"; // 连接Oracle数据库的用户名 private final
	 * static String db_userName = "CX_DM"; // 连接Oracle数据库的密码 private final
	 * static String db_passWord = "cx_123456";
	 */
	// 设置私有的构造方法，确保单例安全
	// 定义数据库连接URL
	private static String db_url = "";
	// 定义Oracle数据库连接驱动
	private static String db_driver = "";
	// 定义连接Oracle数据库的用户名
	private static String db_userName = "";
	// 定义连接Oracle数据库的密码
	private static String db_passWord = "";
	// 定义数据连接对象
	private static Connection conn = null;
	// 定义类的单例对象
	private static ResultSet rs = null;
	private static DBConnection dbConnection;

	private DBConnection(String db_url, String db_driver, String db_userName,String db_passWord) {
		this.db_url = db_url;
		this.db_driver = db_driver;
		this.db_userName = db_userName;
		this.db_passWord = db_passWord;
	}

	// 返回单一对象，同时对数据连接进行初始化
	public static DBConnection getInstance(String db_url, String db_driver,String db_userName, String db_passWord) {
		if (dbConnection == null) {
			dbConnection = new DBConnection(db_url, db_driver, db_userName,db_passWord);
			conn = dbConnection.getConnection();
		}
		return dbConnection;
	}

	// 连接数据库，接收传递过来的数据库连接参数
	private Connection getConnection() {
		try {
			Class.forName(db_driver);
			conn = DriverManager.getConnection(db_url, db_userName, db_passWord);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}

	// 关闭数据库
	public void closeConnection() {
		try {
			if (conn != null) {
				if (!conn.isClosed()) {
					conn.close();
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	// 根据传递过来的sql语句，返回查询结果
	public ResultSet getQueryResult(String sql) {

		try {
			rs = conn.createStatement().executeQuery(sql);
			//rs = st.executeQuery(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		return rs;

	}	

}
